import axios from 'axios'
import store from '@/store'
// import { Spin } from 'iview'
const addErrorLog = errorInfo => {
  // 将errorInfo信息转化为对象
  const { statusText, status, request: { responseURL } } = errorInfo
  let info = {
    type: 'ajax',
    code: status,
    mes: statusText,
    url: responseURL
  }
  // 如果是记日志请求，在store中记录日志。
  if (!responseURL.includes('save_error_logger')) store.dispatch('addErrorLog', info)
}

class HttpRequest {
  // 请求构造函数【baseUrl】
  constructor (baseUrl = baseURL) {
    this.baseUrl = baseUrl
    this.queue = {}
  }
  // 获取内部配置【baseURL+headers】
  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        //
      }
    }
    return config
  }

  destroy (url) {
    delete this.queue[url]
  }
  // 设置拦截器
  interceptors (instance, url) {
    // 请求拦截
    instance.interceptors.request.use(

      // 在发送请求之前做些什么
      config => {
        if (store.state.user.token) {
          config.headers.Authorization = `${store.state.user.token}`
          config.headers.appId = `${store.state.user.userId}`
          config.headers.contentType = 'application/json'
        }
        this.queue[url] = true
        return config
      },
      // 对请求错误做些什么
      error => {
        return Promise.reject(error)
      })
    // 响应拦截
    instance.interceptors.response.use(
      res => {
        this.destroy(url)
        const { data, status } = res
        return { data, status }
      },
      error => {
        this.destroy(url)
        let errorInfo = error.response
        if (!errorInfo) {
          const { request: { statusText, status }, config } = JSON.parse(JSON.stringify(error))
          errorInfo = {
            statusText,
            status,
            request: { responseURL: config.url }
          }
        }
        addErrorLog(errorInfo)
        return Promise.reject(error)
      })
  }

  request (options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}
export default HttpRequest
